<template>
  <view class="container">
    <!-- 消息显示区域 -->
    <scroll-view scroll-y class="message-list" :style="{ height: messageListHeight + 'px' }">
      <block v-for="(item, index) in messages" :key="index">
        <view :class="['message', item.isUser ? 'user-message' : 'ai-message']" v-html="item.htmlText" style="display: inline-block; white-space: pre-line;"></view>
      </block>
    </scroll-view>

    <!-- 输入发送区域 -->
    <view class="input-area">
      <input style="color:white"
        type="text" 
        placeholder="请输入..." 
        v-model="userInput" 
        :disabled="isSending"
        @confirm="sendUserMessage"
      />
      <button @click="sendUserMessage" style="color :white; background-color:#6464be">发送</button>
    </view>
  </view>
</template>

<script>
import config from '@/config.js';
export default {
  data() {
    return {
      userInput: '',
      messages: [],
      isSending: false,
      messageListHeight: 0 // 根据实际情况设置
    };
  },
  methods: {
    sendUserMessage() {
      if (this.userInput.trim() === '' || this.isSending) return;

      const userMessage = { text: this.userInput, htmlText: this.userInput, isUser: true };
      this.messages.push(userMessage);

      this.isSending = true;
      this.sendMessage(this.userInput).finally(() => {
        this.userInput = '';
        this.isSending = false;
      });
    },
    sendMessage(msg) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: `${config.BASE_URL}/chat`,
          method: 'POST',
          data: JSON.stringify({ message: msg }),
          header: {
            'content-type': 'application/json'
          },
          success: (res) => {
            console.log('Server response:', res.data);
            let aiResponse = res.data.response;
            // 将 ** 包围的文本转换为 <strong> 标签包围的文本
            aiResponse = aiResponse.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
            const aiMessage = { text: aiResponse, htmlText: aiResponse, isUser: false };
            this.messages.push(aiMessage);
            resolve();
          },
          fail: () => {
            console.error('Request failed');
            const errorMessage = { text: "小助手没找到答案呢，可以换个问题试试哦。", htmlText: "小助手没找到答案呢，可以换个问题试试哦。", isUser: false };
            this.messages.push(errorMessage);
            reject();
          }
        });
      });
    }
  },
  onLoad() {
    uni.getWindowInfo({
      success: (res) => {
        this.messageListHeight = res.windowHeight - 50; // 减去输入框高度
      }
    });

    // 添加欢迎信息
    const welcomeMessage = {
      text: "你好呀！我是你的星空小助手，就像一本活的天文百科全书。你想知道星星的秘密、月亮的故事，还是太阳系里的趣事呢？有什么关于天空的问题都可以问我哦！准备好后就把问题告诉我吧，我会尽力帮你找到答案的！",
      htmlText: "你好呀！我是你的星空小助手，就像一本活的天文百科全书。你想知道星星的秘密、月亮的故事，还是太阳系里的趣事呢？有什么关于天空的问题都可以问我哦！准备好后就把问题告诉我吧，我会尽力帮你找到答案的！",
      isUser: false
    };
    this.messages.push(welcomeMessage);
  }
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color:#1e1e36;
}

.message-list {
  flex-grow: 1;
  padding: 10px;
  overflow-y: auto;
}

.message {
  margin-bottom: 10px;
  padding: 10px;
  margin-left: 15px;
  border-radius: 10px;
  /* Remove max-width to allow the message bubble to grow */
}

.user-message {
  background-color: #d7fdd4;
  align-self: flex-start;
  margin-right: 10%;
}

.ai-message {
  background-color: #e0f7fa;
  align-self: flex-end;
  margin-right: 10%;
}

.input-area {
  display: flex;
  padding: 10px;
  background-color: #242444;
}

input {
  flex-grow: 1;
  padding: 10px;
  border: none;
  border-radius: 20px;
  margin-right: 10px;
}

button {
  padding: 10px 20px;
  border: none;
  border-radius: 20px;
}
</style>